package com.ejlchina.common.captcha;

import org.springframework.beans.factory.InitializingBean;

import com.ejlchina.common.message.MsgSender;


/**
 * 默认验证码管理器
 * 
 * @author Troy.Zhou
 *
 */
public class DefaultCaptchaManager implements CaptchaManager, InitializingBean {


	/**
	 * 信息发送器
	 */
	private MsgSender msgSender;
	
	/**
	 * 验证码服务
	 */
	private CaptchaService captchaService;
	
	/**
	 * 验证码生成器
	 */
	private CodeGenerator codeGenerator;

	/**
	 * 验证码信息模板名称
	 */
	private String msgTmplName;
	
	/**
	 * 每个号码每日允许发送上限次数
	 * */
	private Integer maxTimesOnePhonePerDay = 20;

	/**
	 * 验证码有效时间
	 */
	private int expireSeconds = 15 * 60;
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		if (captchaService == null) {
			captchaService = new MemoryCaptchaService();
		}
		if (codeGenerator == null) {
			codeGenerator = new RandomNumCodeGenerator();
		}
	}
	
	@Override
	public VerifyResult verify(String phone, String code) {
		if (code == null) {
			return VerifyResult.INVALID;
		}
		Captcha captcha = captchaService.findCaptcha(phone);
		if (captcha == null || captcha.isChecked()) {
			return VerifyResult.INVALID;
		}
		if (captcha.isExpired()) {
			return VerifyResult.EXPIRED;
		}
		if (code.equals(captcha.getCode())) {
			captchaService.markCaptchaChecked(phone, captcha);
			return VerifyResult.SUCSESS;
		} else {
			return VerifyResult.INVALID;
		}
	}
	
	
	@Override
	public SendResult sendCapcha(String phone) {
		return sendCapcha(phone, msgTmplName);
	}
	
	
	@Override
	public SendResult sendCapcha(String phone, String msgTmplName) {
		int sendTimes = captchaService.findSendTimesToday(phone);
		if (sendTimes >= maxTimesOnePhonePerDay) {
			return SendResult.MORE_COUNT;
		}
		String code = codeGenerator.generate();
		if (msgSender.send(phone, msgTmplName, code)) {
			captchaService.save(phone, code, expireSeconds);
			return SendResult.SUCSESS;
		} else {
			return SendResult.FAIL;
		}
	}

	
	public void setCaptchaService(CaptchaService captchaService) {
		this.captchaService = captchaService;
	}

	public void setCodeGenerator(CodeGenerator codeGenerator) {
		this.codeGenerator = codeGenerator;
	}

	public void setMsgSender(MsgSender msgSender) {
		this.msgSender = msgSender;
	}
	
	public void setMsgTmplName(String msgTmplName) {
		this.msgTmplName = msgTmplName;
	}

	public Integer getMaxTimesOnePhonePerDay() {
		return maxTimesOnePhonePerDay;
	}

	public void setMaxTimesOnePhonePerDay(Integer maxTimesOnePhonePerDay) {
		this.maxTimesOnePhonePerDay = maxTimesOnePhonePerDay;
	}
	
	public void setExpireSeconds(int expireSeconds) {
		this.expireSeconds = expireSeconds;
	}

}
